/**
 * Filename: OfficialListAdapter.java
 *
 * @author Firefly
 * @contact postfirefly@163.com
 * @time 2016/3/6 16:23
 */
package com.github.postsanf.yinian.adapter;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.drawee.view.SimpleDraweeView;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.activity.LookSendWebActivity;
import com.github.postsanf.yinian.activity.MainActivity;
import com.github.postsanf.yinian.activity.ShopContactServiceActivity;
import com.github.postsanf.yinian.activity.TimeGoodsAlbumActivity;
import com.github.postsanf.yinian.activity.TimeGoodsDrawActivity;
import com.github.postsanf.yinian.activity.TimeGoodsJointActivity;
import com.github.postsanf.yinian.activity.TimeGoodsLomoPreViewActivity;
import com.github.postsanf.yinian.activity.VoiceCardPreViewActivity;
import com.github.postsanf.yinian.bean.YNOrder;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.utils.ImageOptHelper;
import com.github.postsanf.yinian.utils.StringUtils;
import com.litesuits.http.HttpConfig;
import com.litesuits.http.LiteHttp;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.listener.HttpListener;
import com.litesuits.http.request.StringRequest;
import com.litesuits.http.request.param.HttpMethods;
import com.litesuits.http.response.Response;

import org.json.JSONObject;

import java.util.LinkedHashMap;
import java.util.List;

public class OrderListAdapter extends RecyclerView.Adapter<OrderListAdapter.ViewHolder> {
    public static final int TYPE_HEADER = 0;
    public static final int TYPE_NORMAL = 1;
    private Context context;
    private Activity activity;
    private List<YNOrder> datas;
    private View mHeaderView;
    private int userId;

    public OrderListAdapter(Context context, List<YNOrder> datas, int userid) {
        this.context = context;
        this.activity = (Activity) context;
        this.datas = datas;
        this.userId = userId;
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        TextView order_item_look_send;
        TextView order_item_status;
        ImageView order_item_show;
        LinearLayout order_item_moreinfo;
        TextView order_item_number;
        TextView order_item_time;
        TextView order_item_people;
        TextView order_item_telpheone;
        TextView order_item_address;
        SimpleDraweeView order_item_pic;
        TextView order_shop_name;
        TextView order_shop_price;
        TextView order_shopsnum;
        TextView order_item_contactservice;
        TextView order_item_again_send;

        public ViewHolder(View itemView) {
            super(itemView);
            if (itemView == mHeaderView) return;
            order_item_status = (TextView) itemView
                    .findViewById(R.id.order_item_status);
            order_item_show = (ImageView) itemView
                    .findViewById(R.id.order_item_show);
            order_item_moreinfo = (LinearLayout) itemView
                    .findViewById(R.id.order_item_moreinfo);
            order_item_number = (TextView) itemView
                    .findViewById(R.id.order_item_number);
            order_item_time = (TextView) itemView
                    .findViewById(R.id.order_item_time);
            order_item_people = (TextView) itemView
                    .findViewById(R.id.order_item_people);
            order_item_telpheone = (TextView) itemView
                    .findViewById(R.id.order_item_telpheone);
            order_item_address = (TextView) itemView
                    .findViewById(R.id.order_item_address);
            order_item_pic = (SimpleDraweeView) itemView
                    .findViewById(R.id.order_item_pic);
            order_shop_name = (TextView) itemView
                    .findViewById(R.id.order_shop_name);
            order_shop_price = (TextView) itemView
                    .findViewById(R.id.order_shop_price);
            order_shopsnum = (TextView) itemView
                    .findViewById(R.id.order_shopsnum);
            order_item_contactservice = (TextView) itemView
                    .findViewById(R.id.order_item_contactservice);
            order_item_again_send = (TextView) itemView
                    .findViewById(R.id.order_item_again_send);
            order_item_look_send = ((TextView) itemView.findViewById(R.id.order_item_look_send));
        }

        public void bindData(final YNOrder listItems, final int point) {
            if (listItems != null) {
                order_item_status.setText(listItems.getEbOrderStatus());
                order_item_number.setText(listItems.getEbOrderNumber());
                order_item_time.setText(listItems.getEbOrderPlaceTime());
                order_item_people.setText(listItems.getAddressReceiver());
                order_item_telpheone.setText(listItems.getAddressPhoneNumber());
                order_item_address.setText(listItems.getAddressDetail());
                ImageOptHelper.showFrescoTodayshow(Uri.parse(listItems.getItem().get(0).getEbGoodsPic()), order_item_pic, context);
                order_shop_name.setText(listItems.getItem().get(0).getEbGoodsName());
                order_shop_price.setText("¥" + listItems.getItem().get(0).getEbGoodsPrice());
                order_shopsnum.setText("数量：" + listItems.getItem().get(0).getItemNum());
                order_item_show.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (!listItems.isShow()) {
                            listItems.setShow(true);
                            order_item_moreinfo.setVisibility(View.VISIBLE);
                            order_item_show.setImageResource(R.drawable.order_item_showno);
                        } else {
                            listItems.setShow(false);
                            order_item_moreinfo.setVisibility(View.GONE);
                            order_item_show.setImageResource(R.drawable.order_item_showyes);
                        }
                    }
                });
                final int ebGoodId = listItems.getEbGoodsID();
                order_item_again_send.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        switch (ebGoodId) {
                            case 1:
                                MainActivity.goodsid = 1;
                                context.startActivity(new Intent(context, TimeGoodsAlbumActivity.class));
                                break;
                            case 2:
                                MainActivity.goodsid = 2;
                                context.startActivity(new Intent(context, TimeGoodsAlbumActivity.class));
                                break;
                            case 3:
                                MainActivity.goodsid = 3;
                                context.startActivity(new Intent(context, TimeGoodsAlbumActivity.class));
                                break;
                            case 4:
                                MainActivity.goodsid = 4;
                                context.startActivity(new Intent(context, TimeGoodsAlbumActivity.class));
                                break;
                        }
                    }
                });
                order_item_contactservice.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        context.startActivity(new Intent(context, ShopContactServiceActivity.class));
                    }
                });
                order_item_look_send.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(context, LookSendWebActivity.class);
                        intent.putExtra("ebOrderLogisticsCompany", listItems.getEbOrderLogisticsCompany());
                        intent.putExtra("ebOrderLogisticsNumber", listItems.getEbOrderLogisticsNumber());
//                        Log.d("yuhao", "ebOrderLogisticsNumber="+listItems.getEbOrderLogisticsNumber());
//                        Log.d("yuhao", "ebOrderLogisticsCompany="+listItems.getEbOrderLogisticsCompany());
                        if (listItems.getEbOrderLogisticsCompany() == null || listItems.getEbOrderLogisticsNumber() == null) {
                            final AlertDialog.Builder builder = new AlertDialog.Builder(context);
                            builder.setMessage("对不起，该订单没有物流信息！");
                            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            });
                            builder.create().show();
                        } else {
                            context.startActivity(intent);
                        }
                    }
                });

                order_item_pic.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (listItems.getEbGoodsID() == 1) {
                            if (listItems.getItem().get(0).getItemID() != null) {
                                Log.d("yuhao", "itemID="+listItems.getItem().get(0).getItemID());
                                context.startActivity(new Intent(context, VoiceCardPreViewActivity.class).putExtra("itemID", listItems.getItem().get(0).getItemID()));
                            }
                        } else if (listItems.getEbGoodsID() == 2) {
                            if (listItems.getItem().get(0).getItemID() != null){

                                context.startActivity(new Intent(context, TimeGoodsLomoPreViewActivity.class).putExtra("itemID", listItems.getItem().get(0).getItemID()));
                            }
                        } else if (listItems.getEbGoodsID() == 3) {
                            if (listItems.getItem().get(0).getItemID() != null){

                                context.startActivity(new Intent(context, TimeGoodsJointActivity.class).putExtra("itemID", listItems.getItem().get(0).getItemID()));
                            }
                        } else if (listItems.getEbGoodsID() == 4) {
                            if (listItems.getItem().get(0).getItemID() != null){

                                context.startActivity(new Intent(context, TimeGoodsDrawActivity.class).putExtra("itemID", listItems.getItem().get(0).getItemID()));
                            }
                        }
                    }
                });
            }
        }
    }

    private void EditAddressNext(String type, String addressID, String receiver,
                                 String phone,
                                 String province,
                                 String city,
                                 String area,
                                 String detail, final int point) {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put("userid", String.valueOf(userId));
        mParam.put("type", type);
        if (!StringUtils.isEmpty(addressID)) {
            mParam.put("addressID", addressID);
        }
        mParam.put("receiver", receiver);
        mParam.put("phone", phone);
        mParam.put("province", province);
        mParam.put("city", city);
        mParam.put("area", area);
        mParam.put("detail", detail);
        StringRequest req = new StringRequest(context.getString(R.string.SHOP_URL) + context.getString(R.string.ynManageAddress))
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        try {
                            JSONObject jsonObject = new JSONObject(s.toString());
                            if (jsonObject.optString("msg").equals("success") && jsonObject.optInt("code") == 0) {
                                datas.remove(point);
                                notifyDataSetChanged();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        Toast.makeText(context, CommonConstants.YN_NET_LINK, Toast.LENGTH_SHORT).show();
                    }
                });
        LiteHttp.newApacheHttpClient(new HttpConfig(context)).executeAsync(req);
    }

    public void setHeaderView(View headerView) {
        mHeaderView = headerView;
        notifyItemInserted(0);
    }

    public View getHeaderView() {
        return mHeaderView;
    }

    @Override
    public int getItemViewType(int position) {
        if (mHeaderView == null) return TYPE_NORMAL;
        if (position == 0) return TYPE_HEADER;
        return TYPE_NORMAL;
    }

    private YNOrder getItem(int position) {
        return datas.get(position);
    }

    // 创建ViewHolder
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (mHeaderView != null && viewType == TYPE_HEADER) return new ViewHolder(mHeaderView);
        View convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.yn_item_order, parent, false);
        return new ViewHolder(convertView);
    }

    // 绑定数据到View
    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        if (getItemViewType(position) == TYPE_HEADER) return;
        final int pos = getRealPosition(holder);
        YNOrder listItems = getItem(pos);

        holder.bindData(listItems, pos);
        holder.itemView.setTag(listItems);
    }

    public int getRealPosition(RecyclerView.ViewHolder holder) {
        int position = holder.getLayoutPosition();
        return mHeaderView == null ? position : position - 1;
    }

    @Override
    public int getItemCount() {
        return mHeaderView == null ? datas.size() : datas.size() + 1;
    }
}
